package com.auction.service.impl;

import com.auction.dto.AdminLoginDTO;
import com.auction.exception.BusinessException;
import com.auction.mapper.AdminMapper;
import com.auction.pojo.Admin;
import com.auction.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * 管理员服务实现类
 */
@Service
@Slf4j
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    /**
     * 管理员登录
     * 
     * @param adminLoginDTO
     * @return
     */
    @Override
    public Admin login(AdminLoginDTO adminLoginDTO) {
        String username = adminLoginDTO.getUsername();
        String password = adminLoginDTO.getPassword();

        // 1. 根据用户名查询管理员
        Admin admin = adminMapper.selectByUsername(username);

        // 2. 判断管理员是否存在
        if (admin == null) {
            throw new BusinessException("用户名不存在");
        }

        // 密码比对
        // 对前端传过来的明文密码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(admin.getPassword())) {
            // 密码错误
            throw new BusinessException("密码错误");
        }

        // 返回登录成功信息
        return admin;
    }

    /**
     * 根据ID查询管理员
     * 
     * @param id
     * @return
     */
    @Override
    public Admin getById(Long id) {
        return adminMapper.selectById(id);
    }

}